
var req = null;
var timerID = null;
var state = { };

function startTimer(secs) {
	if(timerID) {
		clearInterval(timerID);
	}
	timerID = null;
	if(secs > 0) {
		timerID = setInterval(fetchState,secs * 1000);
	}
}

function fetchState() {
	if(req==null) {
		req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
	}
	if(req==null) {
		return;
	}
	req.open("GET","/state.js",true)
	req.onreadystatechange = fetchStateChange;
	req.send(null);
}

function fetchStateChange() {
	if(req.readyState == 4 && req.status == 200) {
		var json = eval('('+ req.responseText +')');
		for(key in json) {
			if(typeof key != "string") {
				continue;
			}
			new_value = json[key]
			old_value = state[key]
			/* call for state change when values are different */
			/* interval key is treated slightly differently */
			if(key=='interval' && (old_value != new_value)) {
				stateHasChanged(key,new_value);
			} else if((key in state) && (old_value != new_value)) {
				stateHasChanged(key,new_value);
			}
			state[key] = new_value
		}
	}
}

function stateHasChanged(key,value) {
	/* if key is 'interval' then restart the timer with the new seconds */
	if(key=='interval' && typeof value=="number") {
		startTimer(value)
		return;
	}
	/* find the appropriate DIV element */
	divNode = document.getElementById("block-" + key)
	if(divNode) {
		/* get the iframe tag within the DIV element, and reload */
		for(var i = 0; i < divNode.childNodes.length; i++) {
			var childNode = divNode.childNodes[i]
			if(childNode.nodeType==1) {
				if(navigator.appName == "Microsoft Internet Explorer") {
				    childNode.contentWindow.location.reload(true);
				} else {
				    childNode.src = childNode.src;
				}
			}
		}
	}
}

